package com.hd.until;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.Map.Entry;


import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;


public class TestEif {
	
	// 创建CookieStore实例
    private static CookieStore cookieStore = null;
    private static HttpClientContext context = null;
    private static String response = "";
//    private static String clientId = UUID.randomUUID().toString();
    private static String clientId = "f238ba5db5a24927b1ab100cb16e2f24";
    private static String clientSecret = "cf0b11ab00f341488360856896e9d993";
	
    /*
     * 发送Json
     */
	public String requestTOEifbyJson(String url, String js){
		
		 	HttpResponse httpResponse = null;
	        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
	        try {
	            HttpPost httpPost = new HttpPost(url);
	            StringEntity se = new StringEntity(js, "utf-8");
	            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");    
	            httpPost.setEntity(se);
	            httpResponse = client.execute(httpPost);	            
	            response = printResponse(httpResponse);
	            if(null != httpResponse.getFirstHeader("Set-Cookie")){
	            	if(httpResponse.getFirstHeader("Set-Cookie").getValue().contains("ECF_JSESSIONID")){
	            		String host = httpPost.getURI().getHost();
		                setCookieStore(httpResponse, host);
	            	}
	            }
	            if (cookieStore == null || "".equals(cookieStore)) {
	                String host = httpPost.getURI().getHost();
	                setCookieStore(httpResponse, host);
	            }

	           
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	        } catch (ClientProtocolException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }finally {
	            try {
	                // 关闭流并释放资源
	                client.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	        
	        return response;
	}

	
	/*
     * 发送表单Post
     */
	public static String requestTOEifbyFrom(String url, Map<String, String> parameterMap){
        HttpResponse httpResponse = null;
        UrlEncodedFormEntity postEntity = null;
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        try {
            HttpPost httpPost = new HttpPost(url);
            postEntity = new UrlEncodedFormEntity(getParam(parameterMap), "UTF-8");
            httpPost.setEntity(postEntity);

            httpResponse = client.execute(httpPost);
            response = printResponse(httpResponse);
            if (cookieStore == null || "".equals(cookieStore)) {
                String host = httpPost.getURI().getHost();
                setCookieStore(httpResponse, host);
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                // 关闭流并释放资源
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }
	
	
	/*
     * 发送表单Get
     */
	public static String requestGetTOEifbyFrom(String url, Map<String, String> parameterMap){
        HttpResponse httpResponse = null;
        String getEntity = null;
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        try {
        	getEntity = EntityUtils.toString(new UrlEncodedFormEntity(getParam(parameterMap), "UTF-8"));
            HttpGet httpget = new HttpGet(url + "?" + getEntity);
            
//            httpPost.setEntity(postEntity);

            httpResponse = client.execute(httpget);
            if(null != httpResponse.getFirstHeader("Set-Cookie")){
            	System.out.println(httpResponse.getFirstHeader("Set-Cookie").getValue());
            }
            response = printResponse(httpResponse);
            if (cookieStore == null || "".equals(cookieStore)) {
                String host = httpget.getURI().getHost();
                setCookieStore(httpResponse, host);
            }

           
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                // 关闭流并释放资源
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }
	
	public static String printResponse(HttpResponse httpResponse) throws ParseException, IOException {
        String responseString = "";
        // 获取响应消息实体
        HttpEntity entity = httpResponse.getEntity();
        // 判断响应实体是否为空
        if (entity != null) {
            responseString = EntityUtils.toString(entity);
        }
        return responseString;
    }
	
	
	 public static List<NameValuePair> getParam(Map<String, String> parameterMap) {
	        List<NameValuePair> param = new ArrayList<NameValuePair>();
	        Iterator it = parameterMap.entrySet().iterator();
	        while (it.hasNext()) {
	            Entry parmEntry = (Entry) it.next();
	            param.add(new BasicNameValuePair((String) parmEntry.getKey(),(String) parmEntry.getValue()));
	        }
	        return param;
	    }
	 
	 public static void setCookieStore(HttpResponse httpResponse,String host) {
	        cookieStore = new BasicCookieStore();
	        // JSESSIONID
	        if (null == httpResponse.getFirstHeader("Set-Cookie")) {
	            cookieStore = null;
	        }else {
	            String setCookie = httpResponse.getFirstHeader("Set-Cookie").getValue();
	            if(setCookie.contains("EIF_JSESSIONID")){
	            	String JSESSIONID = setCookie.substring("EIF_JSESSIONID=".length(),setCookie.indexOf(";"));
		            // 新建一个Cookie
		            BasicClientCookie cookie = new BasicClientCookie("EIF_JSESSIONID",JSESSIONID);
		            cookie.setVersion(0);
		            cookie.setDomain(host);
		            cookie.setPath("/");
		            cookieStore.addCookie(cookie);
	            }else if (setCookie.contains("ECF_JSESSIONID")){
	            	String JSESSIONID = setCookie.substring("ECF_JSESSIONID=".length(),setCookie.indexOf(";"));
		            // 新建一个Cookie
		            BasicClientCookie cookie = new BasicClientCookie("ECF_JSESSIONID",JSESSIONID);
		            cookie.setVersion(0);
		            cookie.setDomain(host);
		            cookie.setPath("/");
		            cookieStore.addCookie(cookie);
	            }else{
	            	String JSESSIONID = setCookie.substring("JSESSIONID=".length(),setCookie.indexOf(";"));
		            // 新建一个Cookie
		            BasicClientCookie cookie = new BasicClientCookie("JSESSIONID",JSESSIONID);
		            cookie.setVersion(0);
		            cookie.setDomain(host);
		            cookie.setPath("/");
		            cookieStore.addCookie(cookie);
	            }            
	           
	        }
	    }
	 
	 public void registerEif(String phoneNo){
		 String register_url = "https://qm.hdfax.com/eif-mtp-web/mobile/v1/register/op_register_mobile_user.json";
		 String register = "{\"smsCode\": \"123456\",\"clientId\":\""+ clientId + "\",\"byTpk\": \"d1ff522d7f47c2911543379a29088b7378b740e02be68c63c5efd5cdf7e5ab70e352742fd3f0aa4e09c7536c9ba98e02abd03a4a2ff8d323546678a59b7b37a9a535acabb4d5a6f5e92231f1f89bb404398225f9aff359ab76875f618436c90ad063c874bd0605839c099695714f17b3e79d21787b3c6360f80d1aa74143acd6ed50fb79294ecfe373268db164\",\"fundsToType\": \"1\",\"byKek\": \"8d49577e488c1af687ce3c444b8b42e69450e58b616fa28c2295d098c90795861a4d7a5094e42d062bae2aa5ac3dfdc7922c6b5c75ad753a9a62ad470c20b650fdc5920b39bea19e7721a865da1ec6cac6c7098a8ad239093399629dc2850d02a9c5cc82b51eea42d544e8d8382bda96786dee2ba644e57e1a866e13af5cc5ba\",\"marketChannel\": \"default_channel\",\"appId\": \"001\",\"phoneNumber\": \""+phoneNo +"\"}";
		 String regRsp = requestTOEifbyJson(register_url,register);
		 JSONObject json = JSONObject.fromObject(regRsp); 
		 Assert.assertEquals("1000", json.getString("resultCode"),"注册失败....");
//		 System.out.println(regRsp);;
	 }
	 
	 public void loginEif(String phoneNo){
		 String login_url = "https://qm.hdfax.com/eif-mtp-web/mobile/v1/login/op_personal_login.json";
		 String login = "{\"clientId\": \"" + clientId + "\",\"byTpk\": \"8cf356f2057bc483e8833b1eb9a5dd8de4494a65f7ddf872c616f2ff4b03682e8b1b70d9cfe623bb749ca883e07605012148b9b3549f74d094548108d4c993e0c895ca93c805189c03ad6853fcd4b54022ffd9837ac40082d1c8683e4c8b02ee9af07abace97220ef37a25fa95bfdfc4bf35d0e534d0212a2ecc1c9bc78722c8e40df1a962ee31ec523a569e44\",\"appId\": \"001\",\"phoneNumber\": \"" +phoneNo + "\",\"byKek\": \"88eb89ea8579286bcf5d32aaee9d34489227ee56eb762bbe2a6c6ad7a518361c4fd62915f327014268bccfaec9663e6db4e663868b7df553a06216835c40c1583fbe6f425e0e30f8eea5ee21032c7872b57c30df4bdb3045fdecf0aa23287ab3dea4b79e90fbdd16a3ee77e64e13fde05083ecc9b8112ea1cda5b9a84bb93cf9\"}";
		 String regRsp = requestTOEifbyJson(login_url,login);
		 JSONObject json = JSONObject.fromObject(regRsp); 
		 Assert.assertEquals("1000", json.getString("resultCode"),"登陆失败....");
//		 System.out.println(regRsp);
	 }
	 
	 public void realNameTOEif(String userName,String certId){
		 String realName_url = "https://qm.hdfax.com/eif-mtp-web/mobile/v1/auth/op_real_name_auth.json";
		 String realName = "{\"clientId\": \""+ clientId + "\",\"idCardType\": 1,\"idCardNumber\": \""+ certId + "\",\"appId\": \"001\",\"realName\": \"" + userName +"\"}";
		 String regRsp = requestTOEifbyJson(realName_url,realName);
		 JSONObject json = JSONObject.fromObject(regRsp); 
		 System.out.println(regRsp);
		 Assert.assertEquals("1000", json.getString("resultCode"),"实名失败..");
		 
	 }
	 
	 public void opAuthPage(){
		 String authUrl = "https://quimf.hdfax.com/eff-uim-front-web/authorize/op_auth_page";
		 Map<String,String> map = new HashMap<String, String>();
		 map.put("redirect_uri", "https://qhyb.hengdadai.com/AuthByAuthCode");
		 map.put("client_id", clientId);
		 map.put("scope", "all");
		 map.put("access_type", "offline");
		 map.put("approval_prompt", "force");
//		 map.put("token", token);
		 map.put("response_type", "code");		 
		 map.put("app_source", "1");
		
//		 JSESSIONID=4536216EA7F5D1EF3312C2A2E0AFB8BE
//		 cookieStore.clear();
		 BasicClientCookie cookie = new BasicClientCookie("JSESSIONID","4536216EA7F5D1EF3312C2A2E0AFB8BE");
		 cookieStore.addCookie(cookie);
		 String regRsp = requestGetTOEifbyFrom(authUrl,map);
		 System.err.println(regRsp);
	 
	 }
	 
	 public String getAutoCode(){
		 String token = getToken();
		 String autoCode = "";
		 Map<String,String> map = new HashMap<String, String>();
//		 map.put("redirect_uri", "https://qhyb.hengdadai.com/AuthByAuthCode");
		 map.put("redirect_uri", "http://www.baidu.com");
		 map.put("client_id", clientId);
		 map.put("scope", "all");
		 map.put("access_type", "offline");
		 map.put("approval_prompt", "force");
		 map.put("token", token);
		 map.put("response_type", "code");	 
		 map.put("app_source", "1");
//		 String tjs = "redirect_uri=https%3A%2F%2Fqhyb.hengdadai.com%2FAuthByAuthCode&client_id="+ clientId + "&client_secret=&state=&scope=all&access_type=offline&approval_prompt=force&token=" + token + "&response_type=code&app_source=1";
		 String url = "https://quimf.hdfax.com/eff-uim-front-web/authorize/op_auth_page";
		 String regRsp = requestGetTOEifbyFrom(url,map);
		 System.out.println(regRsp);
		 JSONObject json = JSONObject.fromObject(regRsp);
		 autoCode = json.getString("code");
		 System.out.println("token========" + autoCode);
		 return autoCode;
	 }
	 
	 
	 public String getToken(){
		 String token = "";
		 String tjs = "{\"bizType\":\"100\",\"clientId\":\""+clientId + "\",\"extField\":\"{}\",\"appId\":\"001\"}";
		 String url = "https://qm.hdfax.com/eif-mtp-web/mobile/v1/uni_member/op_get_next_biz_token.json";
		 String regRsp = requestTOEifbyJson(url,tjs);
		 JSONObject json = JSONObject.fromObject(regRsp);
		 token = json.getString("nextToken");
		 System.out.println("token========" + token);
		 return token;
	 }
	 
	 public String queryToken(){
		 String token = "";
		 String js = "{\"authCode\":\"6c5b58602be9efcd8dfac8b711bf7d31\",\"clientId\":\""+ clientId + "\",\"appId\":\"001\"}";
		 String url = "https://qmtp.hengdadai.com//ecf-mtp-web/h5/v1/user/op_query_unim_user_info.json";
		 String regRsp = requestTOEifbyJson(url,js);
		 System.out.println(regRsp);
		 JSONObject json = JSONObject.fromObject(regRsp);
		 token = json.getString("nextToken");
		 System.out.println("token========" + token);
		 return token;
	 }
	 
	 
	 
	 public void createAndRel(){
		 String nextToken = queryToken();
		 String cjs = "{\"token\":\""+ nextToken + "\",\"clientId\":\"" + clientId + "\",\"appId\":\"001\"}";
		 String url = "https://qmtp.hengdadai.com/ecf-mtp-web/h5/v1/user/op_create_and_bind_relationship.json";
		 String regRsp = requestTOEifbyJson(url,cjs);
		 System.out.println(regRsp);
	 }
	 
	 
	 public String getNextToken(){
		 
		 String nextToken = "";
		 String getNextTokenUrl = "https://qm.hdfax.com/eif-mtp-web/mobile/v1/uni_member/op_get_next_biz_token.json";
		 String reqJson = "{\"clientId\": \""+ clientId + "\",\"appId\": \"001\",\"bizType\": \"100\",\"extField\":\"{}\"}";
		 String regRsp = requestTOEifbyJson(getNextTokenUrl,reqJson);
		 JSONObject json = JSONObject.fromObject(regRsp); 
		 System.out.println(regRsp);
		 Assert.assertEquals("1000", json.getString("resultCode"),"获取nextToken失败..");
		 nextToken = json.getString("nextToken");
		 return nextToken;
		 
	 }
	 
	 public String getAuthPage(String token){
		 String accessCode = "";
		 String url = "https://quimf.hdfax.com/eff-uim-front-web/authorize/get_auth_code.form";
		 Map<String,String> map = new HashMap<String, String>();
		 map.put("redirect_uri", "https://qhyb.hengdadai.com/AuthByAuthCode");
		 map.put("client_id", clientId);
		 map.put("scope", "all");
		 map.put("state", new Date().getTime() + "");
		 map.put("access_type", "offline");
		 map.put("approval_prompt", "force");
		 map.put("token", token);
		 map.put("response_type", "code");	 
		 map.put("app_source", "1");
		 map.put("client_secret", clientSecret);
		 String regRsp = requestTOEifbyFrom(url, map);
		 System.out.println("regRsp ========" + regRsp);
		 JSONObject json = JSONObject.fromObject(regRsp); 		
		 Assert.assertEquals("1000", json.getString("respCode"),"获取authPage失败..");
		 accessCode = json.getString("code");
		 return accessCode;
		 
	 }
	 
	 public String getNextTokenByAccessCode(String accesscode){
		 String nextToken = "";
		 String url = "https://qmtp.hengdadai.com/ecf-mtp-web/h5/v1/user/op_query_unim_user_info.json";
		 String reqjson = "{\"authCode\":\"" + accesscode + "\",\"clientId\":\"" + clientId+ "\",\"appId\":\"001\"}";
		 String  regRsp= requestTOEifbyJson(url,reqjson);
		 JSONObject json = JSONObject.fromObject(regRsp); 
		 System.out.println("regRsp11====" + regRsp);
		 Assert.assertEquals("1000", json.getString("resultCode"),"再次获取nextToken失败..");
		 nextToken = json.getString("nextToken");
		 return nextToken;
	 }
	 
	 public void registerToECF(String nextToken){
		 String url = "https://qmtp.hengdadai.com/ecf-mtp-web/h5/v1/user/op_create_and_bind_relationship.json";
		 String reqJson = "{\"token\":\"" + nextToken + "\",\"clientId\":\"" + clientId+ "\",\"appId\":\"001\"}";
		 String  regRsp= requestTOEifbyJson(url,reqJson);
		 JSONObject json = JSONObject.fromObject(regRsp); 
		 Assert.assertEquals("1000", json.getString("resultCode"),"注册ECF失败..");
	 }
	 
	 
	 public static void main(String[] args) {
		
		 TestEif eif = new TestEif();
		 String token = "";
		 String phoneNo = "18900000651";
		 eif.registerEif(phoneNo);
		 eif.loginEif(phoneNo);
		 
		 eif.realNameTOEif("JSD0651", "130100198506023009");
		 
		 token =eif.getNextToken();
		 System.out.println("nextToken=======" + token);
		 String accesscode = eif.getAuthPage(token);
//		 eif.getNextTokenByAccessCode(accesscode);
		 String nextToken = eif.getNextTokenByAccessCode(accesscode);	 
		 eif.registerToECF(nextToken);
		 
	

		 
//		 eif.getAutoCode();
//		 eif.opAuthPage();
	}
}
